package cn.jdemo.unsafe.theUnsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @date 2021/1/15
 */
public class Demo01 {
    public static void main(String[] args) {
        // test01();
        // test02();
        test03();
    }

    /**
     * 输出内容：
     * Exception in thread "main" java.lang.SecurityException: Unsafe
     */
    public static void test01() {
        Unsafe unsafe = Unsafe.getUnsafe();
        System.out.println(unsafe);
    }

    /**
     * 输出内容：
     * java.lang.NoSuchFieldException: theUnsafe
     */
    public static void test02() {
        Class<Unsafe> unsafeClass = Unsafe.class;
        try {
            Field theUnsafe = unsafeClass.getField("theUnsafe");
            theUnsafe.setAccessible(true);
            System.out.println(theUnsafe.get(null));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出内容:
     * sun.misc.Unsafe@64b8f8f4
     */
    public static void test03() {
        Class<Unsafe> unsafeClass = Unsafe.class;
        try {
            Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            System.out.println(theUnsafe.get(null));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
